import { Component, OnInit, ViewChild, OnDestroy, inject } from '@angular/core';
import { PageHeaderModule } from '@delon/abc/page-header';
import { STPage, STComponent, STColumn, STChange, STModule } from '@delon/abc/st';
import { DelonACLModule } from '@delon/acl';
import { DelonFormModule, SFSchema } from '@delon/form';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Api } from 'src/app/shared/api/api';
import { BaseAbilityComponent } from 'src/app/shared/base.ability.component';
import { ResponseCode } from 'src/app/shared/response.code';

import { ClientEditComponent } from './client-edit.component';

@Component({
  selector: 'app-auth2-client',
  templateUrl: './client.component.html',
  imports: [PageHeaderModule, DelonACLModule, DelonFormModule, NzCardModule, STModule, NzButtonModule]
})
export class RegisteredClientComponent extends BaseAbilityComponent implements OnInit, OnDestroy {
  params: NzSafeAny = {};
  searchParams: NzSafeAny = {};
  page: NzSafeAny = {
    records: [],
    current: 1,
    total: 0,
    size: 10
  };
  pagination: STPage = {
    front: false,
    pageSizes: [10, 20, 30, 40, 50],
    total: true,
    showSize: true,
    showQuickJumper: true
  };

  searchSchema: SFSchema = {
    properties: {
      clientId: {
        type: 'string',
        title: 'clientId'
      },
      clientName: {
        type: 'string',
        title: 'clientName'
      }
    }
  };

  @ViewChild('st', { static: true }) st!: STComponent;
  columns: STColumn[] = [
    { title: '序号', type: 'no', width: '80px', fixed: 'left' },
    { title: 'clientId', index: 'clientId', width: '200px', fixed: 'left' },
    { title: 'clientName', index: 'clientName', width: '200px', fixed: 'left' },
    { title: '密码过期时间', index: 'clientSecretExpiresAt', width: '200px' },
    { title: '验证方法', index: 'clientAuthenticationMethods', width: '200px' },
    { title: '授权类型', index: 'authorizationGrantTypes', width: '200px' },
    { title: '授权码模式回调地址', index: 'redirectUris', width: '200px' },
    { title: '退出重定向地址', index: 'postLogoutRedirectUris', width: '200px' },
    { title: '授权范围', index: 'scopes', width: '200px' },
    { title: '是否需要授权确认', index: 'requireAuthorizationConsent', width: '200px', type: 'yn' },
    { title: 'accessToken存活时长(小时)', index: 'accessTokenTimeToLive', width: '200px' },
    { title: '授权码存活时长(分钟)', index: 'authorizationCodeTimeToLive', width: '200px' },
    { title: '设备码存活时长(分钟)', index: 'deviceCodeTimeToLive', width: '200px' },
    { title: 'refreshToken存活时长(天)', index: 'refreshTokenTimeToLive', width: '200px' },
    { title: '是否重用RefreshToken', index: 'reuseRefreshTokens', width: '200px', type: 'yn' },
    {
      title: '操作',
      width: '200px',
      fixed: 'right',
      buttons: [
        {
          text: '查看',
          icon: 'eye',
          type: 'modal',
          modal: {
            component: ClientEditComponent,
            drag: true
          },
          click: () => {
            this.query();
          }
        },
        {
          text: '删除',
          icon: 'delete',
          click: (record: NzSafeAny) => {
            this.delete(record);
          }
        }
      ]
    }
  ];

  protected readonly http = inject(_HttpClient);
  private readonly modal = inject(ModalHelper);
  private readonly modalService = inject(NzModalService);
  private readonly msg = inject(NzMessageService);

  ngOnInit() {
    super.initAbilities();
    this.searchParams = {};
    this.query();
  }
  ngOnDestroy(): void {
    super.clearAbilities();
  }

  change(e: STChange) {
    if (e.type === 'pi' || e.type === 'ps') {
      this.params.size = e.ps;
      this.params.current = e.pi;
      this.query();
    }
  }

  search(event: NzSafeAny) {
    this.searchParams = event;
    this.query();
  }

  query() {
    const current: number = this.params.current || 1;
    const size: number = this.params.size || 10;
    this.http.get(`${Api.BaseClientApi}/page/${current}/${size}`, this.searchParams).subscribe((res: NzSafeAny) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        if (res.data) this.page = res.data;
        else this.msg.warning(res ? (res.message ? res.message : '未知错误') : '未知错误');
      }
    });
  }

  add() {
    this.modal.createStatic(ClientEditComponent, {}, { drag: true }).subscribe(() => this.st.reload());
  }

  delete(record: NzSafeAny) {
    this.modalService.confirm({
      nzTitle: '确定删除吗?',
      nzContent: '<b style="color: red;">如果您确定要删除请点击确定按钮，否则点取消</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () =>
        this.http.delete(`${Api.BaseClientApi}/${record.id}`).subscribe((res: NzSafeAny) => {
          if (res) {
            if (res.code === ResponseCode.SUCCESS) {
              this.st.reload();
              this.msg.success('删除成功');
            } else {
              this.msg.warning(res.message);
            }
          } else {
            this.msg.error('删除失败，未知错误');
          }
        }),
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }
}
